<template>
  <div>
    <post-comment :slug="article.slug" v-on:postComment="onPostComment" />

    <div class="card" v-for="comment in comments" :key="comment.id">
      <template v-if="comment.isEditing">
        <post-comment
          :slug="article.slug"
          v-on:postComment="onPostComment"
          :body="comment.body"
          @not-editing="comment.isEditing = false"
        />
      </template>
      <template v-else>
        <div class="card-block">
          <p class="card-text">{{ comment.body }}</p>
        </div>
        <div class="card-footer">
          <nuxt-link
            :to="{
              name: 'profile',
              params: {
                username: comment.author.username,
              },
            }"
            class="comment-author"
          >
            <img
              :src="comment.author.image"
              class="comment-author-img"
            /> </nuxt-link
          >&nbsp;
          <nuxt-link
            :to="{
              name: 'profile',
              params: {
                username: comment.author.username,
              },
            }"
            class="comment-author"
            >{{ comment.author.username }}</nuxt-link
          >
          <span class="date-posted">{{
            comment.createdAt | date("MMM DD, YYYY")
          }}</span>
          <span
            class="mod-options"
            v-if="comment.author.username === user.username"
          >
            <i
              class="ion-edit"
              @click="editComment(comment.id, comment.isEditing)"
            ></i>
            <i class="ion-trash-a" @click="deleteComment(comment.id)"></i>
          </span>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import {
  getArticleComments,
  postArticleComment,
  deleteArticleComment,
} from "@/api/article";
import { mapState } from "vuex";
import PostComment from "@/pages/article/components/post-comment";

export default {
  name: "ArticleComments",
  props: {
    article: {
      type: Object,
      required: true,
    },
  },
  components: {
    PostComment,
  },
  async mounted() {
    const { data } = await getArticleComments(this.article.slug);
    this.comments = data.comments;
    this.comments.forEach((comment) => {
      this.$set(comment, "isEditing", false);
    });
  },

  data() {
    return {
      comments: [],
    };
  },

  computed: {
    ...mapState(["user"]),
  },
  methods: {
    onPostComment(comment) {
      this.comments.shift(comment);
    },
    async deleteComment(id) {
      await deleteArticleComment(this.article.slug, id);
      this.comments = this.comments.filter((comment) => comment.id !== id);
    },
    editComment(id, isEditing) {
      const comment = this.comments.find((comment) => comment.id === id);
      comment.isEditing = !isEditing;
    },
  },
};
</script>
